<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-container">
        <el-input
          v-model="username"
          placeholder="输入用户名"
          clearable
          @keyup.enter="handleSearch"
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="disabledDate"
          style="margin-left: 20px; width: 400px"
        />

        <el-button
          type="primary"
          @click="handleSearch"
          :loading="loading"
          style="margin-left: 20px"
        >
          <el-icon><Search /></el-icon>
          查询数据
        </el-button>
      </div>
    </el-card>

    <!-- 图表展示区域 -->
    <div class="chart-container">
      <el-card class="chart-card left-chart">
        <div v-loading="loading" class="chart-wrapper">
          <div v-show="sugarData.length === 0" class="empty-tip">
            <el-empty description="暂无血糖数据" />
          </div>
          <div v-show="sugarData.length > 0" ref="sugarChart" style="height: 500px"></div>
        </div>
        <div class="stats-row">
          <el-statistic title="最高血糖" :value="sugarStats.max" suffix="mmol/L" />
          <el-statistic title="平均血糖" :value="sugarStats.avg" suffix="mmol/L" />
          <el-statistic title="测量次数" :value="sugarData.length" />
        </div>
      </el-card>

      <el-card class="chart-card right-chart">
        <div v-loading="loading" class="chart-wrapper">
          <div v-if="pressureData.length === 0" class="empty-tip">
            <el-empty description="暂无血压数据" />
          </div>
          <div v-else ref="pressureChart" style="height: 500px"></div>
        </div>
        <div class="stats-row">
          <el-statistic title="最高收缩压" :value="pressureStats.maxSystolic" suffix="mmHg" />
          <el-statistic title="平均收缩压" :value="pressureStats.avgSystolic" suffix="mmHg" />
          <el-statistic title="平均舒张压" :value="pressureStats.avgDiastolic" suffix="mmHg" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { 
  getBloodSugarData,
  getBloodPressureData 
} from '@/api/healthSys/records'
import { getUserIdByUsername } from '@/api/healthSys/users'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 图表实例
const sugarChart = ref(null)
const pressureChart = ref(null)
let sugarChartInstance = null
let pressureChartInstance = null

// 响应式数据
const username = ref('')
const dateRange = ref([])
const sugarData = ref([])
const pressureData = ref([])
const loading = ref(false)

// 统计指标
const sugarStats = ref({ max: 0, avg: 0 })
const pressureStats = ref({ 
  maxSystolic: 0, 
  avgSystolic: 0,
  avgDiastolic: 0 
})

// 基础图表配置
const getBaseChartOptions = () => ({
  grid: {
    containLabel: true,
    left: 60,
    right: 30,
    bottom: 60,
    top: 30
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(50, 50, 50, 0.9)',
    borderWidth: 0,
    textStyle: {
      color: '#fff',
      fontSize: 14
    }
  },
  xAxis: {
    type: 'category',
    axisLabel: {
      rotate: 45,
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      fontSize: 12
    }
  }
})

// 带重试的初始化方法
const initChartsWithRetry = (retryCount = 3) => {
  return new Promise(async (resolve, reject) => {
    const tryInit = async (attemptsLeft) => {
      try {
        await nextTick()
        if (!sugarChart.value || !pressureChart.value) {
          throw new Error('图表容器未就绪')
        }
        initCharts()
        resolve()
      } catch (error) {
        if (attemptsLeft > 0) {
          setTimeout(() => tryInit(attemptsLeft - 1), 300)
        } else {
          reject(error)
        }
      }
    }
    tryInit(retryCount)
  })
}
// 初始化图表
const initCharts = () => {
  try {
    sugarChartInstance = sugarChartInstance || echarts.init(sugarChart.value)
    pressureChartInstance = pressureChartInstance || echarts.init(pressureChart.value)

    // 血糖图表配置
    sugarChartInstance.setOption({
      ...getBaseChartOptions(),
      title: {
        text: '血糖趋势分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#333'
        }
      },
      yAxis: {
        ...getBaseChartOptions().yAxis,
        name: '血糖值 (mmol/L)'
      },
      series: [{
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { 
          width: 2, 
          color: '#409EFF' 
        },
        itemStyle: { 
          color: '#409EFF' 
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.01)' }
          ])
        }
      }]
    })

    // 血压图表配置
    pressureChartInstance.setOption({
      ...getBaseChartOptions(),
      title: {
        text: '血压趋势分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          color: '#333'
        }
      },
      yAxis: {
        ...getBaseChartOptions().yAxis,
        name: '血压值 (mmHg)'
      },
      legend: {
        data: ['收缩压', '舒张压'],
        top: 10,
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '收缩压',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: { 
            width: 2, 
            color: '#E6A23C' 
          },
          itemStyle: { 
            color: '#E6A23C' 
          }
        },
        {
          name: '舒张压',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: { 
            width: 2, 
            color: '#67C23A' 
          },
          itemStyle: { 
            color: '#67C23A' 
          }
        }
      ]
    })

  } catch (error) {
    console.error('图表初始化失败:', error)
    throw error
  }
}

// 处理搜索
const handleSearch = async () => {
  if (!username.value.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  try {
    loading.value = true
    const startTime = Date.now()

    // 获取用户ID
    const { data: userId } = await getUserIdByUsername(username.value.trim())
    if (!userId) {
      ElMessage.error('用户不存在')
      return
    }

    // 处理日期范围
    const [startDate, endDate] = dateRange.value || [
      dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
      dayjs().format('YYYY-MM-DD')
    ]

    // 并行请求数据
    const [sugarRes, pressureRes] = await Promise.all([
      getBloodSugarData({ userId, startDate, endDate }),
      getBloodPressureData({ userId, startDate, endDate })
    ])

    // 处理数据
    processSugarData(sugarRes.data)
    processPressureData(pressureRes.data)

    // 确保图表实例存在
    if (!sugarChartInstance || !pressureChartInstance) {
      await initChartsWithRetry(2)
    }

    // 最小加载时间保证
    const minLoadTime = 500 - (Date.now() - startTime)
    if (minLoadTime > 0) await new Promise(r => setTimeout(r, minLoadTime))
    updateCharts()

  } catch (error) {
    ElMessage.error(`数据加载失败: ${error.message}`)
  } finally {
    loading.value = false
  }
  await initChartsWithRetry(2)
}

// 更新图表数据
const updateCharts = () => {
  nextTick(() => {
    // 处理血糖图表
    if (sugarChartInstance) {
      const option = sugarChartInstance.getOption()
      option.xAxis[0].data = sugarData.value.map(item => item.date)
      option.series[0].data = sugarData.value.map(item => item.value)
      sugarChartInstance.setOption(option)
    }

    // 处理血压图表
    if (pressureChartInstance) {
      const option = pressureChartInstance.getOption()
      option.xAxis[0].data = pressureData.value.map(item => item.date)
      option.series[0].data = pressureData.value.map(item => item.systolic)
      option.series[1].data = pressureData.value.map(item => item.diastolic)
      pressureChartInstance.setOption(option)
    }
  })
  if (sugarData.value.length === 0) {
  sugarChartInstance.showLoading('default', { text: '暂无数据' })
} else {
  sugarChartInstance.hideLoading()
}
}

// 处理血糖数据
const processSugarData = (rawData) => {
  if (!rawData?.length) {
    sugarData.value = []
    sugarStats.value = { max: 0, avg: 0 }
    sugarChartInstance?.clear()
    return
  }

  const dateMap = rawData.reduce((map, item) => {
    const date = dayjs(item.recordTime).format('YYYY-MM-DD') // 改为完整日期格式
    if (!map.has(date)) map.set(date, [])
    map.get(date).push(Number(item.bloodSugar))
    return map
  }, new Map())

  sugarData.value = Array.from(dateMap.entries())
    .map(([date, values]) => ({
      date,
      value: (values.reduce((a, b) => a + b, 0) / values.length)
    }))
    .sort((a, b) => dayjs(a.date).diff(dayjs(b.date)))

  const values = sugarData.value.map(item => item.value)
  sugarStats.value = {
    max: Math.max(...values).toFixed(1),
    avg: (values.reduce((a, b) => a + b, 0) / values.length).toFixed(1)
  }
}

// 处理血压数据
const processPressureData = (rawData) => {
  if (!rawData?.length) {
    pressureData.value = []
    pressureStats.value = { maxSystolic: 0, avgSystolic: 0, avgDiastolic: 0 }
    pressureChartInstance?.clear()
    return
  }

  const dateMap = rawData.reduce((map, item) => {
    const date = dayjs(item.recordTime).format('MM/DD')
    if (!map.has(date)) map.set(date, { systolic: [], diastolic: [] })
    map.get(date).systolic.push(Number(item.systolic))
    map.get(date).diastolic.push(Number(item.diastolic))
    return map
  }, new Map())

  pressureData.value = Array.from(dateMap.entries())
    .map(([date, data]) => ({
      date,
      systolic: (data.systolic.reduce((a, b) => a + b, 0) / data.systolic.length),
      diastolic: (data.diastolic.reduce((a, b) => a + b, 0) / data.diastolic.length)
    }))
    .sort((a, b) => dayjs(a.date) - dayjs(b.date))

  const systolicValues = pressureData.value.map(item => Number(item.systolic))
  const diastolicValues = pressureData.value.map(item => Number(item.diastolic))

  pressureStats.value = {
    maxSystolic: Math.max(...systolicValues).toFixed(0),
    avgSystolic: (systolicValues.reduce((a, b) => a + b, 0) / systolicValues.length).toFixed(0),
    avgDiastolic: (diastolicValues.reduce((a, b) => a + b, 0) / diastolicValues.length).toFixed(0)
  }
}

// 生命周期
onMounted(async () => {
  await nextTick()
  initChartsWithRetry(3)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  sugarChartInstance?.dispose()
  pressureChartInstance?.dispose()
})

// 窗口变化处理
const handleResize = () => {
  sugarChartInstance?.resize()
  pressureChartInstance?.resize()
}

// 禁用未来日期
const disabledDate = (time) => {
  return time > Date.now()
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.search-container {
  padding: 20px;
  display: flex;
  align-items: center;
}

.chart-container {
  display: flex;
  gap: 20px;
}

.chart-card {
  flex: 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.chart-card.left-chart {
  border-left: 4px solid #409EFF;
}

.chart-card.right-chart {
  border-left: 4px solid #E6A23C;
}

.chart-wrapper {
  height: 500px;
  padding: 20px;
  position: relative;
}

.stats-row {
  display: flex;
  justify-content: space-around;
  padding: 15px;
  background: #fff;
  border-top: 1px solid #eee;
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

@media (max-width: 1200px) {
  .chart-container {
    flex-direction: column;
  }
  
  .chart-card {
    width: 100%;
  }
}
</style>